package com.bosssoft.common.core.filter;

import com.alibaba.fastjson.JSONObject;
import com.bosssoft.common.context.UserInfo;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Arrays;
import java.util.List;

public class TokenUtil {
    private static final Base64.Decoder DECODER = Base64.getDecoder();

    public static List<String> parseToken(String token) {
        String[] jwtTokenItem = token.split("\\.");
        if (jwtTokenItem == null || jwtTokenItem.length < 2) {
            throw new RuntimeException("roleAuthorization 解析的token的第2个元素不存在");
        }
        String sign = token.substring(jwtTokenItem[0].length() + 1 + jwtTokenItem[1].length() + 1);
        return Arrays.asList(jwtTokenItem[0], jwtTokenItem[1], sign);
    }

    public static UserInfo getUserInfoFromToken(String token) {
        List<String> parts = parseToken(token);
        String payload = new String(DECODER.decode(parts.get(1)), StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(payload);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(jsonObject.getLong("userId"));
        userInfo.setUsername(jsonObject.getString("username"));
        userInfo.setRoles(jsonObject.getString("roles"));
        return userInfo;
    }
}
